using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
using System.IO;
using System.Text.RegularExpressions;

public partial class StoredProcedures
{
    [Microsoft.SqlServer.Server.SqlProcedure]
    public static void DeleteJobFiles(string p_filePathPattern, int p_fileRetentionInDays)
    {
        string str = p_filePathPattern.Substring(0, p_filePathPattern.LastIndexOf("\\") + 1);
        DirectoryInfo directoryInfo = new DirectoryInfo(str);
        if (directoryInfo.Exists)
        {
            string searchPattern = new Regex("\\$\\(ESCAPE_NONE\\(STRTDT\\)\\)").Replace(p_filePathPattern.Replace(str, ""), "*");
            FileInfo fileInfo1 = (FileInfo)null;
            DateTime dateTime1 = DateTime.Now;
            DateTime dateTime2 = dateTime1.AddDays((double)(p_fileRetentionInDays * -1));
            foreach (FileInfo fileInfo2 in directoryInfo.GetFiles(searchPattern))
            {
                if (fileInfo1 == null)
                {
                    fileInfo1 = fileInfo2;
                }
                else
                {
                    dateTime1 = fileInfo2.CreationTime;
                    FileInfo fileInfo3;
                    if (dateTime1.CompareTo(fileInfo1.CreationTime) > 0)
                    {
                        fileInfo3 = fileInfo1;
                        fileInfo1 = fileInfo2;
                    }
                    else
                        fileInfo3 = fileInfo2;
                    dateTime1 = fileInfo3.CreationTime;
                    if (dateTime1.CompareTo(dateTime2) < 0)
                    {
                        File.Delete(fileInfo3.FullName);
                        SqlContext.Pipe.Send(string.Format("File {0} deleted.", (object)fileInfo3.Name));
                    }
                }
            }
        }
        else
            SqlContext.Pipe.Send(string.Format("The path {0} does not exist.", (object)str));
    }
}
